package com.xyh.flowershop.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyh.flowershop.cache.RedisCache;
import com.xyh.flowershop.constant.CacheConstant;
import com.xyh.flowershop.context.WebContext;
import com.xyh.flowershop.domain.User;
import com.xyh.flowershop.enums.GenderEnum;
import com.xyh.flowershop.enums.RoleEnum;
import com.xyh.flowershop.mapper.UserMapper;
import com.xyh.flowershop.service.UserService;
import com.xyh.flowershop.vo.req.user.UserReqVo;
import com.xyh.flowershop.vo.req.user.WxUserReqVo;
import com.xyh.flowershop.vo.resp.common.ResultRespVo;
import com.xyh.flowershop.vo.resp.user.UserRespVo;
import com.xyh.flowershop.vo.resp.user.WxUserRespVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.util.Objects;

/**
 * @author 小约翰可汗
 * @className UserServiceImpl
 * @createTime 2024/4/1720:16
 */
@Slf4j
@Service
@Transactional(rollbackFor = RuntimeException.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final RedisCache redisCache;

    @Value("${file.avatar-path}")
    private String basePath;

    public UserServiceImpl(RedisCache redisCache) {
        this.redisCache = redisCache;
    }

    @Override
    public WxUserRespVo findUser(String code, String id) {
        String userId = WebContext.get();
        Object cacheObject = redisCache.getCacheObject(CacheConstant.USER_PREFIX + userId);
        WxUserRespVo userRespVo = null;
        if (Objects.isNull(cacheObject)) {
            userRespVo = baseMapper.selectByCode(code, userId);
            redisCache.setCacheObject(CacheConstant.USER_PREFIX + userRespVo.getId(), userRespVo);
        } else {
            userRespVo = JSONObject.parseObject(JSON.toJSONString(cacheObject), WxUserRespVo.class);
        }
        return userRespVo;
    }

    @Override
    public Boolean updateSelf(WxUserReqVo vo) {
        Object cacheObject = redisCache.getCacheObject(CacheConstant.USER_PREFIX + WebContext.get());
        String avatar = JSON.parseObject(JSON.toJSONString(cacheObject), WxUserRespVo.class).getAvatar();
        User user = new User();
        BeanUtils.copyProperties(vo,user);

        user.setId(WebContext.get());
        user.setGender(GenderEnum.fromInfo(vo.getGender()).getGenderCode().toString());
        int row = baseMapper.updateById(user);
        // 更新缓存的同时删除旧的文件
        removeFile(avatar);
        WxUserRespVo wxUserRespVo = baseMapper.selectByCode("", WebContext.get());
        redisCache.setCacheObject(CacheConstant.USER_PREFIX+WebContext.get(), wxUserRespVo);
        return row > 0;
    }

    @Override
    public Boolean checkUserIsExist(String param) {
        int row = baseMapper.checkUserName(param);
        return row > 0;
    }

    @Override
    public IPage<UserRespVo> findPageUsers(UserReqVo vo) {
        if(Objects.isNull(vo.getPageIndex()) || vo.getPageIndex() == 0){
            vo.setPageIndex(1L);
        }
        if(Objects.isNull(vo.getPageSize()) || vo.getPageSize() == 0){
            vo.setPageIndex(10L);
        }
        IPage<UserRespVo> page = new Page<>(vo.getPageIndex(),vo.getPageSize());
        page = baseMapper.selectUserPage(vo,page);
        return page;
    }

    @Override
    public UserRespVo findUserById(String id) {
        UserReqVo vo = new UserReqVo();
        vo.setId(id);
        IPage<UserRespVo> page = this.findPageUsers(vo);
        if(page == null || page.getRecords().isEmpty()){
            return null;
        }
        return page.getRecords().get(0);
    }

    @Override
    public ResultRespVo deleteUserInfo(String id, String operId) {
        User user = baseMapper.selectById(operId);
        if(RoleEnum.ADMIN.getCode() != user.getRole()){
            return  ResultRespVo.error("非管理员用户，无法删除用户信息");
        }
        return baseMapper.deleteUser(id)? ResultRespVo.success("删除成功") : ResultRespVo.error();
    }


    /**
     * 删除旧文件
     * @param file
     * @return
     */
    private boolean removeFile(String file){
        String filePath = basePath + file.substring(file.lastIndexOf("/"));
        return new File(filePath).delete();
    }

}
